"""
@author:liazylee
@license: Apache Licence
@time: 2022/2/22 13:16
@contact: li233111@gmail.com
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃　永无BUG！   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""

from alipay_sdk.core import alipay
from conf.env import RETRUN_URL, ALIPAY_GATEWAY, NOTIFY_URL

# 返回手机网站支付宝支付路径
from user_info.models import RoomOrder


def wab_order_url(order_id: int, subject: str, total_amount=None, return_url=RETRUN_URL, **kwargs) -> str:
    if total_amount is None:
        total_amount = check_order_no(order_id)
    print(total_amount)
    if (total_amount == 0):
        return "订单号不存在"
    # total_amount = 0.01
    print(total_amount)
    order_string = alipay.api_alipay_trade_wap_pay(
        out_trade_no=order_id,
        total_amount=str(total_amount),
        subject=subject,
        return_url=RETRUN_URL,
        notify_url=NOTIFY_URL,
    )
    return ALIPAY_GATEWAY + order_string


# 确定价格是否一致
def check_order_no(order_id: int, ) -> float:
    a = RoomOrder.objects.filter(order_id=order_id).first()
    print(a, 'a')
    if a:
        totle_price = a.total_price
        return totle_price
        # 返回价格截取两位小数
        # return round(totle_price, 2)
        # return totle_price
    return 0


# 查看订单号是否支付成功
def check_order_status(payment_no: int) -> bool:
    result = alipay.api_alipay_trade_query(out_trade_no=payment_no)
    if result.get("trade_status", "") == "TRADE_SUCCESS":
        return True
    return False


# 支付宝退款
def trade_refund(payment_no: int, refund_amount: float) -> bool:
    result = alipay.api_alipay_trade_refund(out_trade_no=payment_no, refund_amount=str(refund_amount))
    if result.get("code", "") == "10000":
        return True
    return False
